package com.uchedao.vehicledetection.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import com.nostra13.universalimageloader.utils.L;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.config.Api;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.network.HttpRequest;
import com.uchedao.vehicledetection.utils.ProgressDialogUtil;
import com.uchedao.vehicledetection.utils.T;
import com.uchedao.vehicledetection.utils.UploadPicUtil;
import com.uchedao.vehicledetection.utils.Util;
import com.uchedao.vehicledetection.utils.ViewUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class RegistActivity extends CJDBaseActivity {

    private static final int FROM_CAMERA_UP_LOADCARPACTURE = 101;// 拍照获取
    private static final int FROM_PICTURE_UP_LOADCARPACTURE  = 102;// 从图库获取

    private EditText edName,
                    edMobile,
                    edWX,
                    edQQ,
                    edAddr,
                    edShopName,
                    edIdCard;
    private RadioGroup rgGender, rgIsEmployee;
    private Button btnSubmit;
    private ImageView ivAvatar;

    private ImageView ivFront;
    private LinearLayout llFront;
    private Button btnFront;

    private ImageView ivBack;
    private LinearLayout llBack;
    private Button btnBack;

    private RelativeLayout rlCert;
    private ImageView ivCert;
    private LinearLayout llCert;
    private Button btnCert;

    private int gender; // 1 男  2 女
    private int isEmployee; // 1 是  0 否

    private int picCount = 4;
    private int index;
    private final int PIC_AVATAR = 0;
    private final int PIC_FRONT = 1;
    private final int PIC_BACK = 2;
    private final int PIC_CERT = 3;
    private String[] picPath = new String[picCount];
    private String[] picUrl = new String[picCount];

    private String tmpPath;// 临时图片路径
    private AlertDialog pickerDialog;// 图片选取对话框

    @Override
    protected String getActivityTag() {
        return "RegistActivity";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_regist;
    }

    @Override
    protected void initView() {
        edName = (EditText) findViewById(R.id.edRegistName);
        edMobile = (EditText) findViewById(R.id.edRegistMobile);
        edWX = (EditText) findViewById(R.id.edRegistWX);
        edQQ = (EditText) findViewById(R.id.edRegistQQ);
        edAddr = (EditText) findViewById(R.id.edRegistAddr);
        edShopName = (EditText) findViewById(R.id.edRegistShopName);
        edIdCard = (EditText) findViewById(R.id.edRegistIDCard);
        rgGender = (RadioGroup) findViewById(R.id.rgRegistGender);
        rgIsEmployee = (RadioGroup) findViewById(R.id.rgRegistIsEmployee);
        btnSubmit = (Button) findViewById(R.id.btnRegistSubmit);
        ivAvatar = (ImageView) findViewById(R.id.ivRegistAvatar);
        ivFront = (ImageView) findViewById(R.id.ivRegistFront);
        llFront = (LinearLayout) findViewById(R.id.llRegistFront);
        btnFront = (Button) findViewById(R.id.btnRegistFront);
        ivBack = (ImageView) findViewById(R.id.ivRegistBack);
        llBack = (LinearLayout) findViewById(R.id.llRegistBack);
        btnBack = (Button) findViewById(R.id.btnRegistBack);
        rlCert = (RelativeLayout) findViewById(R.id.rlRegistCert);
        ivCert = (ImageView) findViewById(R.id.ivRegistCkbCert);
        llCert = (LinearLayout) findViewById(R.id.llRegistCkbCert);
        btnCert = (Button) findViewById(R.id.btnRegistCkbCert);
    }

    @Override
    protected void initData() {
        setTitle("验车师认证");
        gender = 1;
        isEmployee = 1;
    }

    @Override
    protected void initListener() {
        rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int id) {
                switch(id) {
                    case R.id.rbRegistMale:
                        gender = 1;
                        break;
                    case R.id.rbRegistFemale:
                        gender = 2;
                        break;
                }
            }
        });
        rgIsEmployee.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int id) {
                switch(id) {
                    case R.id.rbRegistYes:
                        isEmployee = 1;
                        rlCert.setVisibility(View.VISIBLE);
                        break;
                    case R.id.rbRegistNo:
                        isEmployee = 0;
                        rlCert.setVisibility(View.GONE);
                        break;
                }
            }
        });
        ivAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerDialog(PIC_AVATAR);
            }
        });
        btnFront.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerDialog(PIC_FRONT);
            }
        });
        ivFront.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerDialog(PIC_FRONT);
            }
        });
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerDialog(PIC_BACK);
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerDialog(PIC_BACK);
            }
        });
        btnCert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerDialog(PIC_CERT);
            }
        });
        ivCert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerDialog(PIC_CERT);
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                register();
            }
        });
    }

    /**
     * 显示图片选取对话框
     */
    public void showPickerDialog(final int index) {
        this.index = index;

        if (pickerDialog == null) {
            CharSequence[] items = {"拍照", "从图片库选择"};
            pickerDialog = new AlertDialog.Builder(this).setTitle("选择")
                    .setItems(items, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                takePhoto();
                            } else {
                                Intent intent = new Intent();
                                /* 开启Pictures画面Type设定为image */
                                intent.setType("image/*");
                                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                                // intent.setAction(Intent.ACTION_GET_CONTENT);
                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                                } else {
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                }
                                startActivityForResult(intent, FROM_PICTURE_UP_LOADCARPACTURE);
                            }
                        }
                    }).create();
        }
        pickerDialog.show();
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
        tmpPath = file.getAbsolutePath();
        Uri uri = Uri.fromFile(file);
        i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(i, FROM_CAMERA_UP_LOADCARPACTURE);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == FROM_CAMERA_UP_LOADCARPACTURE) {
                setBitmap(tmpPath);
            } else if (requestCode == FROM_PICTURE_UP_LOADCARPACTURE) {
                // dat=content://com.android.providers.media.documents/document/image:944
                Uri uri = data.getData();
                tmpPath = Util.getPath(this, uri);
                L.i("uri = " + uri.toString() + " path=" + tmpPath);
                setBitmap(tmpPath);
            }
        }
    }

    public void setBitmap(String path) {
        picPath[index] = path;

        if(TextUtils.isEmpty(path))
            return;
        Bitmap bmp = Util.getimage(path, 329, 249);

        switch(index) {
            case PIC_AVATAR:
                ivAvatar.setImageBitmap(bmp);
                break;

            case PIC_FRONT:
                ivFront.setImageBitmap(bmp);
                llFront.setVisibility(View.GONE);
                break;

            case PIC_BACK:
                ivBack.setImageBitmap(bmp);
                llBack.setVisibility(View.GONE);
                break;

            case PIC_CERT:
                ivCert.setImageBitmap(bmp);
                llCert.setVisibility(View.GONE);
                break;
        }
    }

    public void register() {
        if(ViewUtil.checkEditEmpty(edName, "请输入姓名"))
            return;
        if(ViewUtil.checkEditEmpty(edMobile, "请输入手机号"))
            return;
        if(ViewUtil.checkEditEmpty(edWX, "请输入微信号"))
            return;
        if(ViewUtil.checkEditEmpty(edQQ, "请输入QQ号"))
            return;
        if(ViewUtil.checkEditEmpty(edAddr, "请输入地址"))
            return;
        if(ViewUtil.checkEditEmpty(edShopName, "请输入名称"))
            return;
        if(ViewUtil.checkEditEmpty(edIdCard, "请输入身份证号码"))
            return;
        if(edMobile.getText().length() != 11) {
            ViewUtil.showEditError(edMobile, "请填写正确手机号");
            return;
        }
        if(edIdCard.getText().length() != 18) {
            ViewUtil.showEditError(edIdCard, "请填写正确身份证号");
            return;
        }
        if(TextUtils.isEmpty(picPath[PIC_AVATAR])) {
            T.showShort(this, "请添加验车师照片");
            return;
        }
        if(TextUtils.isEmpty(picPath[PIC_FRONT])) {
            T.showShort(this, "请选添加身份证正面照片");
            return;
        }
        if(TextUtils.isEmpty(picPath[PIC_BACK])) {
            T.showShort(this, "请添加身份证背面照片");
            return;
        }
        if(isEmployee==1 && TextUtils.isEmpty(picPath[PIC_CERT])) {
            T.showShort(this, "请添加车况宝认证证书扫描件");
            return;
        }

        ProgressDialogUtil.showProgressDlg(this, "提交申请");
        uploadPic(PIC_AVATAR);
        uploadPic(PIC_FRONT);
        uploadPic(PIC_BACK);
        if(isEmployee == 1)
            uploadPic(PIC_CERT);
    }

    public void uploadPic(final int index) {
        UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
            @Override
            public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                if(isSucceed)
                    picUrl[index] = result;
                else {
                    ProgressDialogUtil.dismissProgressDlg();
                    T.showShort(RegistActivity.this, "图片上传失败");
                }
                submit();
            }
        };
        new UploadPicUtil(this).upSinglePic("", picPath[index], callback);
    }

    public void submit() {
        if (TextUtils.isEmpty(picUrl[PIC_AVATAR]) || TextUtils.isEmpty(picUrl[PIC_FRONT]) || TextUtils.isEmpty(picUrl[PIC_BACK]) ||
                (isEmployee==1 && TextUtils.isEmpty(picUrl[PIC_CERT]))) {
            return;
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("name", edName.getText().toString());
        params.put("username", edMobile.getText().toString());
        params.put("sex", gender+"");
        params.put("wx_number", edWX.getText().toString());
        params.put("qq_number", edQQ.getText().toString());
        params.put("address", edAddr.getText().toString());
        params.put("shop_name", edShopName.getText().toString());
        params.put("id_card", edIdCard.getText().toString());
        params.put("id_card_photo", picUrl[PIC_FRONT]);
        params.put("id_card_photo_bm", picUrl[PIC_BACK]);
        params.put("photo", picUrl[PIC_AVATAR]);
        params.put("is_ckb_employees", isEmployee+"");
        params.put("ckb_auth_photo", picUrl[PIC_CERT]);
        Request req = HttpRequest.getRequest(HttpRequest.POST, Api.Action.USER_REGVALID, params,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        ProgressDialogUtil.dismissProgressDlg();
                        T.showShort(RegistActivity.this, "提交成功");
                        finish();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProgressDialogUtil.dismissProgressDlg();
                        T.showShort(RegistActivity.this, error.getMessage());
                    }
                }, false);
        addQueue(req);
    }
}
